﻿/* Copyright (c) 2010 EPiServer AB
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using EPiServer.Municipality.Configuration;
using EPiServer.Municipality.Web;
using EPiServer.Municipality.Web.Mail;

namespace EPiServer.Municipality.Templates.Units {
    /// <summary>
    /// 
    /// </summary>
    /// <remarks></remarks>
    /// <example></example>
    public partial class Comment : UserControlBase {
        private readonly Captcha _captcha = new Captcha(3);
        /* *******************************************************************
         * Properties
         * *******************************************************************/
        #region protected string UniqueKey
        /// <summary>
        /// Gets the UniqueKey of the Comment
        /// </summary>
        /// <value></value>
        protected string UniqueKey {
            get {
                return _captcha.UniqueKey;
            }
        }
        #endregion
        #region protected string CheckSum
        /// <summary>
        /// Gets the CheckSum of the Comment
        /// </summary>
        /// <value></value>
        protected string CheckSum {
            get {
                return UniqueKey.ToBase64String();
            }
        }
        #endregion
        #region protected string CreatorValue
        /// <summary>
        /// Get/Sets the CreatorValue of the Comment
        /// </summary>
        /// <value></value>
        protected string CreatorValue {
            get {
                if (Request.Form["creator"] != null)
                    return Request.Form["creator"];
                return String.Empty;
            }
        }
        #endregion
        #region protected string EmailValue
        /// <summary>
        /// Get/Sets the EmailValue of the Comment
        /// </summary>
        /// <value></value>
        protected string EmailValue {
            get {
                if (Request.Form["email"] != null)
                    return Request.Form["email"];
                return String.Empty;
            }
        }
        #endregion
        #region protected string CommentValue
        /// <summary>
        /// Get/Sets the CommentValue of the Comment
        /// </summary>
        /// <value></value>
        protected string CommentValue {
            get {
                if (Request.Form["comment"] != null)
                    return Request.Form["comment"];
                return String.Empty;
            }
        }
        #endregion
        /* *******************************************************************
         * Methods
         * *******************************************************************/
        #region override protected void OnInit(EventArgs e)
        override protected void OnInit(EventArgs e) {
            InitializeComponent();
            base.OnInit(e);
        }
        #endregion
        #region private void InitializeComponent()
        /// <summary>
        /// 
        /// </summary>
        private void InitializeComponent() {
            Load += Page_Load;
        }
        #endregion
        #region private bool Validate()
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private bool Validate() {
            var errors = new List<string>();
            string checksum = Request["checksum"].FromBase64String();
            string uniquekey = Request["uniquekey"];
            if (!string.Equals(checksum, uniquekey, StringComparison.InvariantCultureIgnoreCase)) {
                errors.Add(Translate("/municipality/units/comment/checksumerror"));
            }
            if (string.IsNullOrEmpty(Request.Form["creator"])) {
                errors.Add(Translate("/municipality/units/comment/nameerror"));
            }
            if (string.IsNullOrEmpty(Request.Form["comment"])) {
                errors.Add(Translate("/municipality/units/comment/commenterror"));
            }
            var regex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
            if (!string.IsNullOrEmpty(Request.Form["email"]) && !regex.IsMatch(Request.Form["email"])) {
                errors.Add(Translate("/municipality/units/comment/emailerror"));
            }
            if (errors.Count == 0)
                return true;

            CommentFormErrors.Text += "<div id=\"comment-form-message\" class=\"systemwarning\"><div><strong>" + Translate("/municipality/global/systemwarning") + "</strong><ul>";
            foreach (string error in errors) {
                CommentFormErrors.Text += "<li>" + error + "</li>";
            }
            CommentFormErrors.Text += "</ul></div></div>";
            return false;
        }
        #endregion
        /* *******************************************************************
         *  Event methods 
         * *******************************************************************/
        #region protected void Page_Load(object sender, EventArgs e)
        /// <summary>
        /// This method is called when the Page's Load event has been fired.
        /// </summary>
        /// <param name="sender">The <see cref="object"/> that fired the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> of the event.</param>
        protected void Page_Load(object sender, EventArgs e) {
            if (Request.QueryString["mode"] != Constants.BrowserMode.comment.ToString() && String.IsNullOrEmpty(Request.Form["save"])) {
                Visible = false;
                return;
            }
            if (!string.IsNullOrEmpty(Request.Form["cancel"])) {
                Response.Redirect(CurrentPage.LinkURL);
            } else if (!string.IsNullOrEmpty(Request.Form["save"])) {
                if (Validate()) {
                    CommentFormMessage.Text = MailUtil.SendComment(CurrentPage.PageLink.ID, CreatorValue, EmailValue, CommentValue);
                    CommentFormPlaceHolder.Visible = false;
                }
            }
        }
        #endregion
    }
}